package alex.cicy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class ServerUtils {
    private static Logger logger = LoggerFactory.getLogger(ServerUtils.class);

    /**
     * 获取指定开头的IP，不存在就返回0.0.0.0
     */
    public static String getHostAddress(String prefix) {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while(interfaces.hasMoreElements()) {
                Enumeration<InetAddress> addresses = interfaces.nextElement().getInetAddresses();
                while(addresses.hasMoreElements()) {
                    String address = addresses.nextElement().getHostAddress();
                    if(address.startsWith(prefix)) {
                        return address;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("", e);
        }
        return "0.0.0.0";
    }
}
